package cn.wolfcode.wms.realm;

import cn.wolfcode.wms.domain.Employee;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {
    @Override
    public String getName() {
        return "EmployeeRealm";
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        if (!"zhangsan".equals(principal)) {
            return null;
        }
        Employee currentUser = new Employee();
        currentUser.setName(principal);
        currentUser.setPassword("1");
        currentUser.setAdmin(true);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(), getName());
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Employee currentUser = (Employee) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<String> roles = new ArrayList<String>();
        roles.addAll(Arrays.asList("HR MGR", "ORDER MGR"));
        authorizationInfo.addRoles(roles);
        List<String> perms = new ArrayList<String>();
        perms.addAll(Arrays.asList("employee:view", "employee:delete"));
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }
}
